import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { Button, Form, Input, Table, Space, Popconfirm } from "antd";
import http from "../../utils/http";

import "./index.scss";

export default function Posts() {
  const navigate = useNavigate();
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0);
  const [params, setParams] = useState({
    _page: 1,
    _limit: 10,
    title_like: "",
  });
  const token = useSelector((state) => state.user.token);

  // 表格列
  const columns = [
    {
      title: "操作",
      key: "action",
      dataIndex: "id",
      width: 200,
      /**
       * 自定义渲染的内容
       * @param {*} text  当指定了 dataIndex 的话，就为当前渲染行的 dataIndex 所指定的字段的值。否则与 record 一样
       * @param {*} record 当前渲染行的数据
       * @param {*} index 当前渲染行的下标
       * @returns
       */
      render: (text, record, index) => {
        return (
          <Space>
            <Button onClick={() => handleEdit(record.id)}>编辑</Button>
            <Popconfirm
              title="你确定要删除嘛?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                handleDel(record.id);
              }}
            >
              <Button danger>删除</Button>
            </Popconfirm>
          </Space>
        );
      },
    },
    { title: "Id", dataIndex: "id", key: "id" },
    { title: "标题", dataIndex: "title", key: "title" },
    { title: "内容", dataIndex: "body", key: "body" },
    { title: "用户Id", dataIndex: "userId", key: "userId" },
  ];

  /**
   * 获取Posts数据
   */
  async function getData() {
    console.log(params, "===");
    const response = await http.get("/posts", {
      // ？号传参
      params: {
        ...params,
        // 默认就是使用id做的排序
        _sort: "id",
        // 倒序
        _order: "desc",
      },
    });
    setTotal(response.headers["x-total-count"]);
    setDataSource(response.data);
  }

  /**
   * 页码或 pageSize 改变的回调
   */
  function onChange(page, pageSize) {
    // 先修改 params
    setParams((params) => ({
      ...params,
      _page: page,
      _limit: pageSize,
    }));
    // 再调用接口获取数据
    // getData();
  }

  /**
   * 搜索
   */
  function onSearch(values) {
    const { searchValue } = values;
    setParams((params) => ({
      ...params,
      _page: 1, // 搜索可能没有这么多数据,默认请求第一页
      title_like: searchValue,
    }));
  }

  /**
   * 处理删除
   */
  async function handleDel(id) {
    try {
      await http.delete(`/posts/${id}`);
      // 删除成功
      //  1. 重新请求新数据
      getData();
      //  2. 删除当前行数据
    } catch (error) {
      // 删除失败
      console.error(error.message);
    }
  }

  function handleEdit(id) {
    navigate(`/posts-edit/${id}`);
  }

  useEffect(() => {
    // 默认请求第一页数据
    getData();
  }, [params]);

  return (
    <div className="posts">
      <h1>
        帖子 - <Link to="/posts-add">新增帖子</Link>
      </h1>

      <Form layout="inline" onFinish={onSearch}>
        <Form.Item name="searchValue">
          <Input placeholder="请输入标题" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>

      <Table
        rowKey="id"
        dataSource={dataSource}
        columns={columns}
        pagination={{
          total: total,
          position: ["topLeft"],
          onChange: onChange,
        }}
      />
    </div>
  );
}
